//
//  UwantJsonEncoder.swift
//  uwantgoeasy
//
//  Created by 冯传宝 on 12/10/15.
//  Copyright © 2015 uwantsoft. All rights reserved.
//

import Foundation

class UwantJsonEncoder {
    
    func encode(msg: Message)->NSData{
        let jsonMsg:String = msg.jsonAsString()
        let length:Int = jsonMsg.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
        let msgBytes:[UInt8] = Array(jsonMsg.utf8)
        let msgLengthBytes = toByteArray(length)
        let combinedMsg:[UInt8] = msgLengthBytes+msgBytes
        return NSData(bytes: combinedMsg, length: length+4)
    }
    
    func toByteArray(value: Int) -> [UInt8] {
        var msgLength = [UInt8](count: 4, repeatedValue: 0)
        
        for i in 0...3 {
            msgLength[i] = UInt8(0x0000FF & value >> Int((3 - i) * 8))
        }
        return msgLength
    }
}
